package DB;

use strict;
use warnings;
use DBI;

sub new
{
  my ($class, %args) = @_;

  bless (\%args, $class);
}

# won't always run, but if it does we might as well cleanup
sub DESTROY
{
  my ($self) = @_;
  $self->disconnect;
}

sub _dsn
{
  my ($self) = @_;

  sprintf ('DBI:mysql:database=%s;host=%s;port=%d', $self->{database},
    $self->{host}, $self->{port});
}

sub connect
{
  my ($self) = @_;
  $self->{dsn} = $self->_dsn;
  $self->{dbh} = DBI->connect ($self->{dsn}, $self->{user}, $self->{pass});
}

sub disconnect
{
  my ($self) = @_;

  return unless ($self->{dbh});

  if ($self->{show_global_status})
  {
    $self->{show_global_status}->finish;
  }
  $self->{dbh}->disconnect;
  delete ($self->{dbh});
}

sub get_global_status
{
  my ($self) = @_;

  unless ($self->{dbh})
  {
    $self->connect;
  }
  unless ($self->{show_global_status})
  {
    $self->{show_global_status} = $self->prepare ('show /*!50002 global */ status');
  }

  my $sth = $self->{show_global_status};
  # TODO: error handling
  $sth->execute;
  my %vals;
  foreach (@{$sth->fetchall_arrayref})
  {
    $vals{$_->[0]} = $_->[1];
  }
  $vals{time} = time;
  \%vals;
}

sub get_master_status
{
  my ($self) = @_;

  unless ($self->{dbh})
  {
    $self->connect;
  }
  unless ($self->{show_master_status})
  {
    $self->{show_master_status} = $self->prepare ('show master status');
  }

  my $sth = $self->{show_master_status};
  # TODO: error handling
  $sth->execute;

  $sth->fetchrow_hashref;
}

sub get_slave_status
{
  my ($self) = @_;

  unless ($self->{dbh})
  {
    $self->connect;
  }
  unless ($self->{show_slave_status})
  {
    $self->{show_slave_status} = $self->prepare ('show slave status');
  }

  my $sth = $self->{show_slave_status};
  # TODO: error handling
  $sth->execute;

  $sth->fetchrow_hashref;
}

sub prepare
{
  my ($self, $sql) = @_;

  unless ($self->{dbh})
  {
    $self->connect;
  }

  $self->{dbh}->prepare ($sql);
}

1;
